package com.tonann.system.utils;

import com.alibaba.fastjson2.JSONArray;
import com.tonann.common.constant.CacheConstants;
import com.tonann.common.core.domain.entity.SysUser;
import com.tonann.common.core.redis.RedisCache;
import com.tonann.common.utils.StringUtils;
import com.tonann.common.utils.spring.SpringUtils;

import java.util.Collection;
import java.util.List;

/**
 * 用户工具类
 *
 * @author ruoyi
 */
public class SysUserUtils {
    /**
     * 分隔符
     */
    public static final String SEPARATOR = ",";

    /**
     * 设置用户缓存
     *
     * @param key        参数键
     * @param sysUserList 用户数据列表
     */
    public static void setSysUserCache(String key, List<SysUser> sysUserList) {
        SpringUtils.getBean(RedisCache.class).setCacheObject(getCacheKey(key), sysUserList);
    }

    /**
     * 获取用户缓存
     *
     * @param key 参数键
     */
    public static List<SysUser> getSysUserCache(String key) {
        JSONArray arrayCache = SpringUtils.getBean(RedisCache.class).getCacheObject(getCacheKey(key));
        if (StringUtils.isNotNull(arrayCache)) {
            return arrayCache.toList(SysUser.class);
        }
        return null;
    }

    /**
     * 根据用户ID获取用户
     *
     * @param userId 用户ID
     * @return 用户
     */
    public static SysUser getSysUserBySysUserId(Long userId) {
        SysUser appSysUser = SpringUtils.getBean(RedisCache.class).getCacheObject(getCacheKey("userId:") + userId);
        if (StringUtils.isNotNull(appSysUser)) {
            return appSysUser;
        }
        return null;
    }

    public static void setSysUserBySysUserId(SysUser sysUser) {
        SpringUtils.getBean(RedisCache.class).setCacheObject(getCacheKey("userId:") + sysUser.getUserId(), sysUser);
    }

    /**
     * 删除指定用户缓存
     *
     * @param key 用户键
     */
    public static void removeSysUserCache(String key) {
        SpringUtils.getBean(RedisCache.class).deleteObject(getCacheKey("userId:") + key);
    }

    /**
     * 清空用户缓存
     */
    public static void clearSysUserCache() {
        Collection<String> keys = SpringUtils.getBean(RedisCache.class).keys(CacheConstants.SYS_USER_KEY + "*");
        SpringUtils.getBean(RedisCache.class).deleteObject(keys);
    }

    /**
     * 设置cache key
     *
     * @param configKey 参数键
     * @return 缓存键key
     */
    public static String getCacheKey(String configKey) {
        return CacheConstants.SYS_USER_KEY + configKey;
    }
}
